package com.todaynews.frame.ui.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Toast;
import androidx.core.content.ContextCompat;
import com.todaynews.R;
import com.todaynews.frame.asynctask.TaskExecutor;
import com.todaynews.frame.model.InfoResult;
import com.todaynews.frame.model.MsgBean;
import com.todaynews.frame.okhttp.OkEntityListRequest;
import com.todaynews.frame.okhttp.OkEntityRequest;
import com.todaynews.frame.okhttp.OkHttpTask;
import com.todaynews.frame.okhttp.OkSimpleRequest;
import com.todaynews.frame.okhttp.SimpleOkHttpListener;
import com.todaynews.frame.theme.ThemeHelper;
import com.todaynews.frame.ui.alerter.Alerter;
import com.todaynews.frame.ui.alerter.OnHideAlertListener;
import com.todaynews.frame.ui.alerter.OnShowAlertListener;
import com.todaynews.frame.ui.barlibrary.ImmersionBar;
import com.todaynews.frame.ui.barlibrary.OSUtils;
import com.todaynews.ui.me.UserLoginActivity;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import me.imid.swipebacklayout.lib.SwipeBackLayout;
import me.imid.swipebacklayout.lib.app.SwipeBackActivity;

public abstract class BaseThemeActivity extends SwipeBackActivity {

    private ActivityManager activityManager = ActivityManager.getActivityManager();
    private EventBus eventBus;
    private Toast toast = null;
    private SwipeBackLayout swipeBackLayout;
    private InputMethodManager inputMethodManager;
    private ThemeHelper themeHelper;
    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    InfoResult infoResult = (InfoResult) msg.obj;
                    int state = infoResult.getState();
                    if(state == -4){
                        Intent i = new Intent(BaseThemeActivity.this, UserLoginActivity.class);
                        //i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP );
                        startActivity(i);
                        finish();
                    }else{
                        if(infoResult.isSuccess()){
                            onSuccess(infoResult.getTag(),infoResult);
                        }else {
                            onFail(infoResult.getTag(),infoResult);
                        }
                    }
                    break;
                default:break;
            }
        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if(null != activityManager) {
            activityManager.putActivity(this);
        }
        //把设置布局文件的操作交给继承的子类
        setContentView(getLayoutResId());
        //初始化沉浸式
        initImmersionBar();
        initSwipeBack();
        setScreenVertical(this);
        eventBus = EventBus.getDefault();
        eventBus.register(this);
        init();
        loadData();
    }

    @Override
    protected void onResume() {
        super.onResume();
        // 非必加
        // 如果你的app可以横竖屏切换，适配了华为emui3系列系统手机，并且navigationBarWithEMUI3Enable为true，
        // 请在onResume方法里添加这句代码（同时满足这三个条件才需要加上代码哦：1、横竖屏可以切换；2、华为emui3系列系统手机；3、navigationBarWithEMUI3Enable为true）
        // 否则请忽略
        if (OSUtils.isEMUI3_x() && isImmersionBarEnabled()) {
            ImmersionBar.with(this).init();
        }
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        if (isImmersionBarEnabled()) {
            // 非必加
            // 如果你的app可以横竖屏切换，适配了4.4或者华为emui3.1系统手机，并且navigationBarWithKitkatEnable为true，
            // 请务必在onConfigurationChanged方法里添加如下代码（同时满足这三个条件才需要加上代码哦：1、横竖屏可以切换；2、android4.4或者华为emui3.1系统手机；3、navigationBarWithKitkatEnable为true）
            // 否则请忽略
            ImmersionBar.with(this).init();
        }
    }

    @Override
    public void finish() {
        super.finish();
        hideSoftKeyBoard();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        inputMethodManager = null;
        if(null != activityManager) {
            activityManager.removeActivity(this);
        }
        if (isImmersionBarEnabled()) {
            ImmersionBar.with(this).destroy();
        }
    }

    protected void initImmersionBar() {
        if (isImmersionBarEnabled()) {
            //在BaseActivity里初始化
            //ImmersionBar.with(this).init();
            ImmersionBar.with(this).navigationBarColor(R.color.colorPrimary).init();
        }
    }

    private void initSwipeBack(){
        if(isSupportSwipeBackEnabled()){
            // 可以调用该方法，设置是否允许滑动退出
            setSwipeBackEnable(true);
            swipeBackLayout = getSwipeBackLayout();
            // 设置滑动方向，可设置EDGE_LEFT, EDGE_RIGHT, EDGE_ALL, EDGE_BOTTOM
            swipeBackLayout.setEdgeTrackingEnabled(SwipeBackLayout.EDGE_LEFT);
            // 滑动退出的效果只能从边界滑动才有效果，如果要扩大touch的范围，可以调用这个方法
            //swipeBackLayout.setEdgeSize(200);
        }else {
            setSwipeBackEnable(false);
        }
    }
    /**
     * 设置Activity的显示方向为横向
     *
     * @param activity
     */
    private void setScreenHorizontal(Activity activity) {
        activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
    }

    /**
     * 设置Activity的显示方向为垂直方向
     *
     * @param activity
     */
    private void setScreenVertical(Activity activity) {
        activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    }
    //===================================alerter==========================================
    public void showAlert(String msg){
        Alerter.create(this)
                .setText(msg)
                .disableOutsideTouch()
                .setDuration(700)
                .show();
    }

    private void showAlertDefault() {
        Alerter.create(this)
                .setTitle("Alert Title")
                .setText("Alert text...")
                .disableOutsideTouch()
                .show();
    }

    private void showAlertColoured() {
        Alerter.create(this)
                .setTitle("Alert Title")
                .setText("Alert text...")
                .setBackgroundColor(R.color.colorAccent)
                .show();
    }

    private void showAlertWithIcon() {
        Alerter.create(this)
                .setText("Alert text...")
                .setIcon(R.drawable.alerter_ic_face)
                .show();
    }

    private void showAlertTextOnly() {
        Alerter.create(this)
                .setText("Alert text...")
                .show();
    }

    private void showAlertWithOnClick() {
        Alerter.create(this)
                .setTitle("Alert Title")
                .setText("Alert text...")
                .setDuration(10000)
                .setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Toast.makeText(BaseThemeActivity.this, "OnClick Called", Toast.LENGTH_LONG).show();
                    }
                })
                .show();
    }

    private void showAlertVerbose() {
        Alerter.create(BaseThemeActivity.this)
                .setTitle("Alert Title")
                .setText("The alert scales to accommodate larger bodies of text. " +
                        "The alert scales to accommodate larger bodies of text. " +
                        "The alert scales to accommodate larger bodies of text.")
                .show();
    }

    private void showAlertCallbacks(){
        Alerter.create(BaseThemeActivity.this)
                .setTitle("Alert Title")
                .setText("Alert text...")
                .setDuration(10000)
                .setOnShowListener(new OnShowAlertListener() {
                    @Override
                    public void onShow() {
                        Toast.makeText(BaseThemeActivity.this, "Show Alert", Toast.LENGTH_LONG).show();
                    }
                })
                .setOnHideListener(new OnHideAlertListener() {
                    @Override
                    public void onHide() {
                        Toast.makeText(BaseThemeActivity.this, "Hide Alert", Toast.LENGTH_LONG).show();
                    }
                })
                .show();
    }

    private void showAlertInfiniteDuration() {
        Alerter.create(BaseThemeActivity.this)
                .setTitle("Alert Title")
                .setText("Alert text...")
                .enableInfiniteDuration(true)
                .show();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void handlerMeg(MsgBean msgBean) {

    }

    public void showToast(String msg) {
        if (toast == null) {
            toast = Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT);
        } else {
            toast.setText(msg);
        }
        toast.show();
    }

    public int getColor(Context context, int id) {
        return ContextCompat.getColor(context, id);
    }

    public void hideSoftKeyBoard() {
        View localView = getCurrentFocus();
        if (this.inputMethodManager == null) {
            this.inputMethodManager = ((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE));
        }
        if ((localView != null) && (this.inputMethodManager != null)) {
            this.inputMethodManager.hideSoftInputFromWindow(localView.getWindowToken(), 2);
        }
    }
    /**
     * 跳转到某个Activity
     * @param activity
     * @param targetActivity
     */
    public void switchTo(Activity activity, Class<? extends Activity> targetActivity, boolean finish) {
        switchTo(activity, new Intent(activity, targetActivity),finish);
    }

    public void switchTo(Activity activity, Intent intent, boolean finish) {
        activity.startActivity(intent);
        if(finish){
            finish();
        }
        //overridePendingTransition(R.anim.alpha_out, R.anim.alpha_in);
    }
    // -------------------- BaseActivity的辅助封装 --------------------- //

    public abstract boolean isImmersionBarEnabled();
    /**
     * 是否支持滑动返回
     *
     * @return
     */
    public abstract boolean isSupportSwipeBackEnabled();

    /**
     * 返回当前Activity布局文件的id
     *
     * @return
     */
    public abstract int getLayoutResId();

    /**
     * 初始化的一些操作
     */
    public abstract void init();

    /**
     * 加载网络数据
     */
    public abstract void loadData();

    /**
     * 网络数据返回成功
     */
    protected abstract void onSuccess(int what, InfoResult t);

    /**
     * 网络数据返回失败
     */
    protected abstract void onFail(int what, InfoResult t);

    public EventBus getEventBus() {
        return eventBus;
    }

    public ThemeHelper getThemeHelper() {
        return themeHelper;
    }

    public void setThemeHelper(ThemeHelper themeHelper) {
        this.themeHelper = themeHelper;
    }

    //-------------------------- okhttp -----------------------------//
    public <T> void requestOkhttpEntityList(OkEntityListRequest<T> okEntityListRequest){
        SimpleOkHttpListener simpleOkHttpListener = new SimpleOkHttpListener(){
            @Override
            public void dataSucceed(int what, InfoResult t) {
                super.dataSucceed(what, t);
                t.setTag(what);
                Message msg = handler.obtainMessage();
                msg.what = 0;
                msg.obj = t;
                handler.sendMessage(msg);
            }

            @Override
            public void dataFailed(int what, InfoResult t) {
                super.dataFailed(what, t);
                t.setTag(what);
                Message msg = handler.obtainMessage();
                msg.what = 0;
                msg.obj = t;
                handler.sendMessage(msg);
            }
        };
        OkHttpTask okHttpTask = new OkHttpTask(okEntityListRequest,simpleOkHttpListener);
        TaskExecutor.getInstance().start(okHttpTask);
    }

    public <T> void requestOkhttpEntity(OkEntityRequest<T> okEntityRequest){
        SimpleOkHttpListener simpleOkHttpListener = new SimpleOkHttpListener(){
            @Override
            public void dataSucceed(int what, InfoResult t) {
                super.dataSucceed(what, t);
                t.setTag(what);
                Message msg = handler.obtainMessage();
                msg.what = 0;
                msg.obj = t;
                handler.sendMessage(msg);
            }

            @Override
            public void dataFailed(int what, InfoResult t) {
                super.dataFailed(what, t);
                t.setTag(what);
                Message msg = handler.obtainMessage();
                msg.what = 0;
                msg.obj = t;
                handler.sendMessage(msg);
            }
        };
        OkHttpTask okHttpTask = new OkHttpTask(okEntityRequest,simpleOkHttpListener);
        TaskExecutor.getInstance().start(okHttpTask);
    }

    public <T> void requestOkhttpSimple(OkSimpleRequest<T> tOkSimpleRequest){
        SimpleOkHttpListener simpleOkHttpListener = new SimpleOkHttpListener(){
            @Override
            public void dataSucceed(int what, InfoResult t) {
                super.dataSucceed(what, t);
                t.setTag(what);
                Message msg = handler.obtainMessage();
                msg.what = 0;
                msg.obj = t;
                handler.sendMessage(msg);
            }

            @Override
            public void dataFailed(int what, InfoResult t) {
                super.dataFailed(what, t);
                t.setTag(what);
                Message msg = handler.obtainMessage();
                msg.what = 0;
                msg.obj = t;
                handler.sendMessage(msg);
            }
        };
        OkHttpTask okHttpTask = new OkHttpTask(tOkSimpleRequest,simpleOkHttpListener);
        TaskExecutor.getInstance().start(okHttpTask);
    }
}
